﻿(function (app) {
    //公共服务
    app.factory('common', ['$http', 'config', '$q', 'msg', function ($http, config, $q, msg) {
        return {
            //经营范围
            getSetting: function (category) {
                return $http({
                    url: config.server + 'api/setting/get/' + category,
                    method: "get"
                })
            },
            //选择图片
            chooseImage: function (cameraOptions) {
                var deferred = $q.defer();
                var defaultCameraOptions = {
                    quality: 50,
                    sourceType: 1,
                    allowEdit: true,
                    encodingType: 0,//0为jpg,1为png
                    targetHeight: 112,
                    targetWidth: 112
                };
                var options = angular.extend(defaultCameraOptions, cameraOptions);
                var sheetOptions = {
                    title: '选择图片方式',
                    buttonLabels: ['拍摄照片', '从图库选择'],
                    addCancelButtonWithLabel: '取消',
                    androidEnableCancelButton: true
                };
                window.plugins.actionsheet.show(sheetOptions, function (index) {
                    switch (index) {
                        case 1: //拍摄图片
                            options.sourceType = 1;
                            break;
                        case 2://从图库选择
                            options.sourceType = 2;
                            break;
                        default:
                            return;
                            deferred.resolve();
                            break;
                    }
                    navigator.camera.getPicture(function (imageUri) {
                        if (imageUri) {
                            deferred.resolve(imageUri);
                        } else {
                            deferred.reject('图片未找到');
                        }
                    }, function (error) {
                      
                        deferred.reject(error);
                    }, options);
                });
                return deferred.promise;
            },
            setAvator: function () {//上传头像
                var deferred = $q.defer();
                this.chooseImage().then(function (imageUri) {
                    msg.text('上传中');
                    var uploadOptions = new FileUploadOptions();
                    uploadOptions.fileKey = "avatar";
                    uploadOptions.fileName = "avatar.jpg";
                    uploadOptions.mimeType = "image/jpeg";
                    uploadOptions.httpMethod = 'post';
                    uploadOptions.chunkedMode = true;
                    var token = 'Bearer ' + localStorage['token'];
                    uploadOptions.headers = { "Authorization": token };
                    var ft = new FileTransfer();
                  
                    ft.upload(imageUri, encodeURI(config.server + "api/auth/avatar"), function (sucess) {
                        msg.hide();
                        deferred.resolve(sucess);
                      //  alert('上传成功' + JSON.stringify(sucess));
                    }, function (fail) {
                        msg.hide();
                        deferred.reject(fail);
                       // alert('上传失败' + JSON.stringify(fail));
                    }, uploadOptions);
                });
                return deferred.promise;
            },
            uploadFiles:function () {//通用上传图片
                var deferred = $q.defer();
                var options = {
                    sourceType: 2,
                    allowEdit: false,
                    encodingType: 0,//0为jpg,1为png
                    targetHeight: 500,
                    targetWidth: 500
                };
                navigator.camera.getPicture(function (imageUri) {
                    //alert(imageUri);
                    if (imageUri) {
                        var uploadOptions = new FileUploadOptions();
                        uploadOptions.fileKey = "store";
                        uploadOptions.fileName = "store.jpg";
                        uploadOptions.mimeType = "image/jpeg";
                        uploadOptions.httpMethod = 'post';
                        uploadOptions.chunkedMode = true;
                        var token = 'Bearer ' + localStorage['token'];
                        uploadOptions.headers = { "Authorization": token };
                        var ft = new FileTransfer();
                        uploadOptions.params = { tag: "picture" };
                        ft.upload(imageUri, encodeURI(config.server + "api/attachment/upload"), function (sucess) {
                            deferred.resolve(sucess);
                         //  alert('上传成功' + JSON.stringify(sucess));
                        }, function (fail) {
                            deferred.reject(fail);
                           //alert('上传失败' + JSON.stringify(fail));
                        }, uploadOptions);
                    } else {
                        deferred.reject('图片未找到');
                    }
                }, function (error) {
                    // alert(error);
                    deferred.reject(error);
                }, options);
               
                return deferred.promise;
            },
            continue_consume: function (data) {
                var deferred = $q.defer();
                $http({
                    url: config.server + 'api/service/continue_consume',
                    method: "post",
                    data: data
                }).success(function (result) {
                    console.log("result pay:"+JSON.stringify(result));
                    var payInfo = result.data.orderString;
                    if (data.pay_type == "alipay_app") {
                        //支付宝
                        console.log("result AliPay");
                        cordova.plugins.AliPay.pay(payInfo, function success(e) {
                            //e.resultStatus  状态代码  e.result  本次操作返回的结果数据 e.memo 提示信息
                            //e.resultStatus  9000  订单支付成功 ;8000 正在处理中  调用function success
                            //e.resultStatus  4000  订单支付失败 ;6001  用户中途取消 ;6002 网络连接出错  调用function error
                            //当e.resultStatus为9000时，请去服务端验证支付结果
                            //  alert('状态码：' + e.resultStatus);
                            if (e.resultStatus == '9000') {
                                deferred.resolve(e.resultStatus);
                            } else {
                                deferred.reject(e);
                            }
                        }, function error(e) {
                            deferred.reject(e);
                        });
                    }
                    if (data.pay_type== "wechatpay_app") { //微信
                        window.wxpay.payment({
                            appid: payInfo.appid,
                            noncestr: payInfo.noncestr,
                            package: payInfo.package,
                            partnerid: payInfo.partnerid,
                            prepayid: payInfo.prepayid,
                            timestamp: payInfo.timestamp,
                            sign: payInfo.sign
                        }, function success(msg) {
                            console.log("wxpay success:"+JSON.stringify(msg));
                            deferred.resolve(msg);
                        }, function error(e) {
                            console.log("wxpay error:"+JSON.stringify(e));
                            deferred.reject(e);
                        })
                    }
                }).error(function (erro) {
                  //  alert(JSON.stringify(erro));
                    deferred.reject(erro);
                });
                return deferred.promise;
            },
            pay: function (data) {
                var deferred = $q.defer();
                $http({
                    url: config.server + 'api/merchant/charge',
                    method: "post",
                    data: data
                }).success(function (result) {
                    console.log("result pay:"+JSON.stringify(result));
                    var payInfo = result.data.orderString;
                    if (data.type == 1) {
                        //支付宝
                        cordova.plugins.AliPay.pay(payInfo, function success(e) {
                            //e.resultStatus  状态代码  e.result  本次操作返回的结果数据 e.memo 提示信息
                            //e.resultStatus  9000  订单支付成功 ;8000 正在处理中  调用function success
                            //e.resultStatus  4000  订单支付失败 ;6001  用户中途取消 ;6002 网络连接出错  调用function error
                            //当e.resultStatus为9000时，请去服务端验证支付结果
                            //  alert('状态码：' + e.resultStatus);
                            if (e.resultStatus == '9000') {
                                deferred.resolve(e.resultStatus);
                            } else {
                                deferred.reject(e);
                            }
                        }, function error(e) {
                            deferred.reject(e);
                        });
                    }
                    if (data.type==2) { //微信
                        window.wxpay.payment({
                            appid: payInfo.appid,
                            noncestr: payInfo.noncestr,
                            package: payInfo.package,
                            partnerid: payInfo.partnerid,
                            prepayid: payInfo.prepayid,
                            timestamp: payInfo.timestamp,
                            sign: payInfo.sign
                        }, function success(msg) {
                            console.log("wxpay success:"+JSON.stringify(msg));
                            deferred.resolve(msg);
                        }, function error(e) {
                            console.log("wxpay error:"+JSON.stringify(e));
                            deferred.reject(e);
                        })
                    }
                }).error(function (erro) {
                  //  alert(JSON.stringify(erro));
                    deferred.reject(erro);
                });
                return deferred.promise;
            }
        };
    }]);
})(angular.module('app.services'));